﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace ScreenSnapshotManager
{
    public class SnapshotManager
    {
        Int32 interval = 30;
        String finalPath;
        String basePath;
        String currentUserName;
        DateTime dateTime;

        public SnapshotManager()
        {
            // get currently logged in user name
            currentUserName = Environment.UserName;

            dateTime = DateTime.Now;

            // get the base path for storing snapshots - i.e. C:\ProgramData\SnapshotManager\Snapshots\
            basePath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\SnapshotManager\\Snapshots\\";

            // create directory path
            finalPath = basePath + currentUserName + "\\" + dateTime.Year + "\\" + dateTime.Month + "\\" + dateTime.Day;

            // create directory if already does not exist
            if (!Directory.Exists(finalPath))
            {
                Directory.CreateDirectory(finalPath);
            }
        }


        public void StartTakingSnapshots()
        {
            while (true)
            {
                // take snapshot now
                this.TakeSnapShotNow();

                // Take the snap shot after every 30 secs :)
                Thread.Sleep(TimeSpan.FromSeconds(interval));
            }
        }


        /// <summary>
        /// Takes the snap shot of the screen every 30 seconds
        /// </summary>
        private void TakeSnapShotNow()
        {
            try
            {
                // get screen bounds
                Rectangle bounds = Screen.PrimaryScreen.Bounds;

                // create the image name.
                dateTime = DateTime.Now;
                String imagePath = String.Format("{0}\\{1}_{2}_{3}.png", finalPath, dateTime.Hour, dateTime.Minute, dateTime.Second);

                // Create the Bitmap & Graphics Object 
                using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb))
                {
                    using (Graphics graphics = Graphics.FromImage(bitmap))
                    {
                        // copy pixels from screen to graphics object
                        graphics.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy);
                    }

                    // save the captured image in the specified directory
                    bitmap.Save(imagePath, ImageFormat.Jpeg);
                }
            }
            catch { }
        }
    }
}
